package com.iwhalecloud.bss.kite.cucc.service.pos.handler.impl;


import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.util.KiteDateUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.common.util.SeqUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.reception.ICustReceptionService;
import com.iwhalecloud.bss.kite.cucc.client.dto.cust.CuccContextCustDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.KiteCustomerInfoReq;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosAttrDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosUserDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.scene.CuccCustInfoDTO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.CommonUtil;
import com.iwhalecloud.bss.kite.cucc.service.batch.BatchAcceptUtil;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.IKitePosSceneHandler;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.KitePosHandlerContext;
import com.iwhalecloud.bss.kite.cucc.service.util.ChangeTypeUtils;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.inst.*;
import com.iwhalecloud.bss.kite.service.ord.pos.vo.KitePosOfferInstVO;
import com.iwhalecloud.bss.kite.service.ord.pos.vo.KitePosOfferObjInstRelVO;
import com.iwhalecloud.bss.kite.service.ord.pos.vo.KitePosProdInstVO;
import com.ztesoft.bss.base.staticdata.CoreDataOffer;
import com.ztesoft.bss.common.bo.UserInfo;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.bss.common.util.ContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class KitePosUserHandler extends KitePosBaseUserHandler implements IKitePosSceneHandler {

    @Autowired
    private ICustReceptionService custReceptionService;
    @Autowired
    IOperateSceneInstService operateSceneInstService;

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @SuppressWarnings("unchecked")
    @Override
    public void handle(KitePosHandlerContext context) {
        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(context.getSceneInstId());
        if (KiteStringUtils.equalsAny(kiteSceneInst.getServiceOfferId(), LocalServiceOfferConsts.SERVICE_OFFER_COP_MEMBER_JOIN, LocalServiceOfferConsts.SERVICE_OFFER_COP_MEMBER_QUIT)) {
            //return;
        }
        List<KitePosUserDTO> users = querySceneInstService
            .getExtParameterValue(context.getSceneInstId(), "serialNumber");

        if (BatchAcceptUtil.isBatchSign(context.getSceneInstId())
            && KiteStringUtils.isNotEmpty(context.getOfferInstId())) {
            users = querySceneInstService.getExtParameterValue(context.getSceneInstId(),
                "batchSignUser_" + context.getOfferInstId());
        }

        Date createDate = querySceneInstService.getSceneInst(context.getSceneInstId()).getCreateDate();
        String createDateStr = KiteDateUtils.formatDate(createDate, KiteDateUtils.DATE_TIME_FORMAT_14);
        String bizType = context.getPosDto().getOrder().getBizType();

        if (KiteStringUtils
            .equalsAny(kiteSceneInst.getServiceOfferId(), LocalServiceOfferConsts.SERVICE_OFFER_COLLECTION_GROUP_ADD,
                LocalServiceOfferConsts.SERVICE_OFFER_COLLECTION_GROUP_DEL)) {
            users = Lists.newArrayList();
            List<Map<String, Object>> groupUserInfos = new ArrayList<>();
            if (KiteStringUtils.equals(LocalServiceOfferConsts.SERVICE_OFFER_COLLECTION_GROUP_ADD,
                kiteSceneInst.getServiceOfferId())) {
                groupUserInfos = querySceneInstService
                    .getExtParameterValue(context.getSceneInstId(), "addGroupUserInfos");
                dealGroupAdd(context, users, kiteSceneInst, createDateStr, groupUserInfos);
            }
            if (KiteStringUtils.equals(LocalServiceOfferConsts.SERVICE_OFFER_COLLECTION_GROUP_DEL,
                kiteSceneInst.getServiceOfferId())) {
                groupUserInfos = querySceneInstService
                    .getExtParameterValue(context.getSceneInstId(), "delGroupUserInfos");
                dealGroupDel(context, users, kiteSceneInst, createDateStr, groupUserInfos);
            }
            List<KitePosUserDTO> userList = querySceneInstService.getExtParameterValue(context.getSceneInstId(), "serialNumber");
            if (KiteListUtils.isEmpty(userList)) {
                operateSceneInstService.putExtParameter(context.getSceneInstId(), "serialNumber", users);
            }
        }
        else if (KiteListUtils.isEmpty(users) || (
            KiteStringUtils.isEqual(ServiceOfferConsts.SERVICE_OFFER_ORDER, kiteSceneInst.getServiceOfferId())
                && !KiteStringUtils.isEqual(kiteSceneInst.getAskSource(), LocalKeyConsts.ASK_SOURCE_ORDER))) {
            users = Lists.newArrayList();
            Map<String, KitePosOfferInstVO> giftOfferInstMap = context.getPosSceneBO().getGiftOfferInstMap();
            if (KiteMapUtils.isNotEmpty(giftOfferInstMap)) {
                this.packageGiftUserAttr(context, users, giftOfferInstMap, createDateStr);
            }
            else if (CuccPosServiceUtils.isBatchAccept(kiteSceneInst.getSceneInstId())) {
                KitePosUserDTO templateUser = packagePosUser(context, kiteSceneInst, createDateStr, bizType);
                Map<String, KitePosOfferInstVO> mainOfferInstMap = context.getPosSceneBO().getMainOfferInstMap();
                List<String> existNumbers = new ArrayList<>();
                for (KitePosOfferInstVO mainOfferInst : mainOfferInstMap.values()) {
                    List<KiteProdInst> prodInstList = querySceneInstService
                        .listProdInstsFromOfferInst(context.getCustId(), mainOfferInst.getInstId());
                    for (KiteProdInst prodInst : prodInstList) {
                        KitePosUserDTO userDTO = KiteObjectUtils.clone(templateUser);
                        String userId = getUserId(context.getSceneInstId(), mainOfferInst.getOfferInst().getInstId(),
                            InstType.MAIN_OFFER_INST, context.getCustDto());
                        if (KiteStringUtils.isEmpty(userId)) {
                            BssException.throwOut("用户信息校验", "用户信息校验", "用户实例标识userId通过用户中心获取失败，请重新提交订单。");
                        }
                        userDTO.setInstanceId(SeqUtils.getNext("SEQ_USER_ID"));
                        String serialNumber = prodInst.getAttrValue("serial_number");
                        System.out.println("serial_number:" + serialNumber);
                        if (KiteStringUtils.isEmpty(serialNumber) || existNumbers.contains(serialNumber)) {
                            serialNumber = getSerialNumber(context);
                            if (KiteStringUtils.isEmpty(serialNumber)) {
                                BssException.throwOut("用户信息校验", "用户信息校验", "业务号码通过用户中心获取失败，请重新提交订单。");
                            }
                        }
                        existNumbers.add(serialNumber);
                        userDTO.setSerialNumber(serialNumber);
                        operateSceneInstService
                            .putExtParameter(context.getSceneInstId(), "business_number", serialNumber);
                        operateSceneInstService.putExtParameter(context.getSceneInstId(), "instanceId", userDTO.getInstanceId());
                        userDTO.setUserId(userId);
                        users.add(userDTO);
                    }
                }
            }
            else {
                String userId = getUserId(context.getSceneInstId(), kiteSceneInst.getRootInstId(), InstType.MAIN_OFFER_INST, context
                    .getCustDto());
                if (KiteStringUtils.isEmpty(userId)) {
                    BssException.throwOut("用户信息校验", "用户信息校验", "用户实例标识userId通过用户中心获取失败，请重新提交订单。");
                }
                KitePosUserDTO user = packagePosUser(context, kiteSceneInst, createDateStr, bizType);
                user.setInstanceId(SeqUtils.getNext("SEQ_USER_ID"));
                user.setUserId(userId);
                String serialNumber = getSerialNumber(context);
                // 退单不校验，app甩单退单无业务号码
                if (KiteStringUtils.isEmpty(serialNumber) && !KiteStringUtils.isEqual(context.getOpType(), "CANCEL")) {
                    BssException.throwOut("用户信息校验", "用户信息校验", "业务号码通过用户中心获取失败，请重新提交订单。");
                }
                user.setSerialNumber(serialNumber);
                operateSceneInstService
                    .putExtParameter(context.getSceneInstId(), "business_number", serialNumber);
                operateSceneInstService.putExtParameter(context.getSceneInstId(), "instanceId", user.getInstanceId());
               /* if("2000991".equals(cateId)||"2100949".equals(cateId)||"2000993".equals(cateId)){
                    List<KitePosAttrDTO> attrList = user.getAttrs();
                    if (KiteListUtils.isEmpty(attrList)) {
                        attrList = new ArrayList<>();
                    }
                    this.packageUserAttrsJf(attrList, user, context, createDateStr,cateId);
                }*/

                users.add(user);
            }
            context.getPosDto().setUsers(users);
        }
        else {
            users.forEach(user -> {
                user.setOfferCatagoryId(this.getOfferCatagoryId(user.getInstanceId(), context.getPosDto().getGoods()));
                //非二次业务需要生成实例ID
                if(KiteStringUtils.isNotEmpty(user.getInstanceId())){
                    user.setInstanceId(user.getInstanceId());
                }else{
                    user.setInstanceId(SeqUtils.getNext("SEQ_USER_ID"));
                }
                if (!CuccPosServiceUtils.isProdModify(context.getSceneInstId())) {
                        /* 订单中心配套改造,归集后的转单报文中实例ID不替换为订单中心的ID
                        //数据来源是订单中心不替换（即订单修改、重提、补录等环节，实例ID不重新生成）
                        if (!KiteStringUtils.equals(LocalKeyConsts.ASK_SOURCE_ORDER, askSource)) {
                            user.setInstanceId(SeqUtils.getNext("SEQ_USER_ID"));
                        }
                        */
                    user.setCityCode(context.getCustDto().getLanId());
                    user.setProvinceCode(context.getCustDto().getProvinceCode());
                }
                this.setUserDiffCode(user, kiteSceneInst);
                if (!ServiceOfferConsts.SERVICE_OFFER_ORDER.equals(kiteSceneInst.getServiceOfferId())
                    && KeyConsts.IFTRUE_T.equals(querySceneInstService
                    .getExtParameterValue(context.getSceneInstId(), LocalKeyConsts.BUSI_CHANGE_SCENE))) {
                    user.setInstanceId(CommonUtil.getInstanceId(LocalKeyConsts.YH_INST_CODE, user.getInstanceId()));
                }
                operateSceneInstService
                    .putExtParameter(context.getSceneInstId(), "business_number", user.getSerialNumber());
                operateSceneInstService.putExtParameter(context.getSceneInstId(), "instanceId", user.getInstanceId());
                // 0511 改造计费周期、付费类型、计费类型、缴费周期、账务周期放在user节点传给订单中心
                // kite_template_module_rel没有集团用户信息模块，实例数据中会没有用户信息，此时取原有的
                String changeCycleVal = querySceneInstService.getCommonAttrValue(context.getSceneInstId(), "ORD10235");
                if (KiteStringUtils.isNotEmpty(changeCycleVal)) {
                    user.setChargeCycle(changeCycleVal);
                }
                String payModeVal = querySceneInstService.getCommonAttrValue(context.getSceneInstId(), "ORD10236");
                if (KiteStringUtils.isNotEmpty(payModeVal)) {
                    user.setPayMode(payModeVal);
                }
                String billTypeVal = querySceneInstService.getCommonAttrValue(context.getSceneInstId(), "ORD10240");
                if (KiteStringUtils.isNotEmpty(billTypeVal)) {
                    user.setBillType(billTypeVal);
                }
                String feeCycleVal = querySceneInstService.getCommonAttrValue(context.getSceneInstId(), "ORD10233");
                if (KiteStringUtils.isNotEmpty(feeCycleVal)) {
                    user.setFeeCycle(feeCycleVal);
                }
                String accountCycleVal = querySceneInstService.getCommonAttrValue(context.getSceneInstId(), "ORD10234");
                if (KiteStringUtils.isNotEmpty(accountCycleVal)) {
                    user.setAccountCycle(accountCycleVal);
                }

                List<KitePosAttrDTO> attrList = user.getAttrs();
                if (KiteListUtils.isEmpty(attrList)) {
                    attrList = new ArrayList<>();
                }

                if (CuccPosServiceUtils.isRouteUser(context.getSceneInstId(), context.getCustId())) {
                    String userLocation = querySceneInstService
                        .getCommonAttrValue(context.getSceneInstId(), "user_location");
                    if (!KiteStringUtils.isEmpty(userLocation)) {
                        user.setProvinceCode(userLocation.split(",")[0]);
                        String userName = querySceneInstService.getCommonAttrValue(context.getSceneInstId(), "group_user_name");
                        if (KiteStringUtils.isNotEmpty(userName)) {
                            user.setName(userName);
                        }
                        user.setCityCode(userLocation.split(",").length > 1 ? userLocation.split(",")[1] : "");
                        user.setDistrictCode(userLocation.split(",").length > 2 ? userLocation.split(",")[2] : "");
                        //国际业务特殊处理，针对没有区县的客户，把地市信息作为区县传下去
                        UserInfo simpleLoginInfo = ContextUtil.getLoginInfo().getUserInfo();
                        if(KiteStringUtils.isEmpty(user.getDistrictCode())&&simpleLoginInfo.getPostProvinceNbr().startsWith("48")||simpleLoginInfo.getPostProvinceNbr().startsWith("49")){
                            user.setDistrictCode(user.getCityCode());
                        }
                    }
                    //用户信息变更修改用户归属地打标2
                    KiteAttr userLocationChangeType = querySceneInstService
                        .getCommonAttr(context.getSceneInstId(), "user_location");
                    if (Objects.nonNull(userLocationChangeType)) {
                        if (!KiteStringUtils.equals(userLocationChangeType.getOriginValue(), userLocationChangeType.getValue())
                            && KiteStringUtils.isNotEmpty(userLocationChangeType.getOriginValue())) {
                            user.setChangeType(ChangeTypeUtils.CHANGE_TYPE_M);
                        }
                    }
                    String name = querySceneInstService.getCommonAttrValue(context.getSceneInstId(), "group_user_name");
                    if (!KiteStringUtils.isEmpty(name)) {
                        user.setName(name);
                    }
                    this.packageUserAttrs(attrList, user, context, createDateStr);
                    // 用户信息变更可以修改集团用户名称 ChangeType传2用户中心才会修改值
                    KiteAttr groupUserName = querySceneInstService
                        .getCommonAttr(context.getSceneInstId(), "group_user_name");
                    if (Objects.nonNull(groupUserName)) {
                        if (!KiteStringUtils.equals(groupUserName.getOriginValue(), groupUserName.getValue())
                            && KiteStringUtils.isNotEmpty(groupUserName.getOriginValue())) {
                            user.setChangeType(ChangeTypeUtils.CHANGE_TYPE_M);
                        }
                    }
                    KiteAttr chargeCycle = querySceneInstService.getCommonAttr(context.getSceneInstId(), "ORD10235");
                    if (Objects.nonNull(chargeCycle)) {
                        if (!KiteStringUtils.equals(chargeCycle.getOriginValue(), chargeCycle.getValue())) {
                            user.setChangeType(ChangeTypeUtils.CHANGE_TYPE_M);
                        }
                    }
                    KiteAttr payMode = querySceneInstService.getCommonAttr(context.getSceneInstId(), "ORD10236");
                    if (Objects.nonNull(payMode)) {
                        if (!KiteStringUtils.equals(payMode.getOriginValue(), payMode.getValue())) {
                            user.setChangeType(ChangeTypeUtils.CHANGE_TYPE_M);
                        }
                    }
                    KiteAttr billType = querySceneInstService.getCommonAttr(context.getSceneInstId(), "ORD10240");
                    if (Objects.nonNull(billType)) {
                        if (!KiteStringUtils.equals(billType.getOriginValue(), billType.getValue())) {
                            user.setChangeType(ChangeTypeUtils.CHANGE_TYPE_M);
                        }
                    }
                    KiteAttr feeCycle = querySceneInstService.getCommonAttr(context.getSceneInstId(), "ORD10233");
                    if (Objects.nonNull(feeCycle)) {
                        if (!KiteStringUtils.equals(feeCycle.getOriginValue(), feeCycle.getValue())) {
                            user.setChangeType(ChangeTypeUtils.CHANGE_TYPE_M);
                        }
                    }
                    KiteAttr accountCycle = querySceneInstService.getCommonAttr(context.getSceneInstId(), "ORD10234");
                    if (Objects.nonNull(accountCycle)) {
                        if (!KiteStringUtils.equals(accountCycle.getOriginValue(), accountCycle.getValue())) {
                            user.setChangeType(ChangeTypeUtils.CHANGE_TYPE_M);
                        }
                    }

                    if (!CuccPosServiceUtils.isProdModify(context.getSceneInstId())) {
                        user.setChangeType(ChangeTypeUtils.CHANGE_TYPE_A);
                    }
                }
                else {
                    // 落老集客的产品 user节点下的集团用户名称需要传修改后的值
                    user.setName(querySceneInstService.getCommonAttrValue(context.getSceneInstId(), "group_user_name"));
                    // 落老集客的产品 user节点下的attrs不需要

               /*     if("2000991".equals(cateId)||"2100949".equals(cateId)||"2000993".equals(cateId)){
                        List<KitePosAttrDTO> attrList1 = user.getAttrs();
                        if (KiteListUtils.isEmpty(attrList1)) {
                            attrList1 = new ArrayList<>();
                        }
                        this.packageUserAttrsJf(attrList1, user, context, createDateStr,cateId);
                    }else if (KiteListUtils.isNotEmpty(user.getAttrs())) {*/
                        user.setAttrs(null);
                 /*   }*/
                }
                if (ServiceOfferConsts.SERVICE_OFFER_TRANSFER.equals(kiteSceneInst.getServiceOfferId())) {
                    //过户业务客户信息需要重新调整
                    String newCustId = kiteSceneInst.getNewCustId();
                    String sceneInstId = context.getSceneInstId();
                    // 从缓存里面取
                    Map<String, Object> extParameter = querySceneInstService.getExtParameter(sceneInstId);
                    Object newCust = extParameter.get(sceneInstId + "_transNewCustDTO");
                    CuccCustInfoDTO newCustDto = Objects.nonNull(newCust) ?
                        (CuccCustInfoDTO) newCust :
                        queryNewCustInfo(newCustId);
                        // UseCustInstId和useCustomer.instanceId进行关联，由于没有传useCustomer节点，所以该节点不传
//                    user.setUseCustInstId(newCustId);
                    user.setProvinceCode(newCustDto.getProvinceCode());
                    user.setCityCode(newCustDto.getEparchyCity());
                    user.setDistrictCode(newCustDto.getEparchyArea());
                    String userName = querySceneInstService
                        .getCommonAttrValue(context.getSceneInstId(), "groupNewCustName");
                    if (KiteStringUtils.isEmpty(userName)) {
                        userName = newCustDto.getCustName();
                    }
                    user.setName(userName);
                    user.setChangeType(ChangeTypeUtils.CHANGE_TYPE_M);
                }
            });
        }
        context.getPosDto().setUsers(users);

    }

    private void dealGroupDel(KitePosHandlerContext context, List<KitePosUserDTO> users, KiteSceneInst kiteSceneInst,
        String createDateStr, List<Map<String, Object>> groupUserInfos) {
        for (Map<String, Object> groupUserInfo : groupUserInfos) {
            KitePosUserDTO user = new KitePosUserDTO();
            user.setUserId(KiteMapUtils.getString(groupUserInfo, "MEM_USER_ID"));
            user.setSerialNumber(KiteMapUtils.getString(groupUserInfo, "MEM_SERIAL_NUMBER").toUpperCase());
            user.setName(KiteMapUtils.getString(groupUserInfo, "MEM_USER_NAME"));
            user.setInstanceId(SeqUtils.getNext("SEQ_USER_ID"));
//            operateSceneInstService
//                .putExtParameter(context.getSceneInstId(), "business_number", user.getSerialNumber());
//            operateSceneInstService.putExtParameter(context.getSceneInstId(), "instanceId", user.getInstanceId());
            List<KitePosAttrDTO> attrList = new ArrayList<>();
            user.setOpenDate(KiteMapUtils.getString(groupUserInfo, "START_DATE"));

            user.setProvinceCode(KiteMapUtils.getString(groupUserInfo, "MEM_PROVINCE_CODE"));
            user.setCityCode(KiteMapUtils.getString(groupUserInfo, "MEM_CITY_CODE"));
            user.setDistrictCode(KiteMapUtils.getString(groupUserInfo, "MEM_EPARCHY_CODE"));

            this.addUserSourceAttr(attrList, groupUserInfo, createDateStr);
            this.packageUserAttrs(attrList, user, context, createDateStr);
            user.setUserDiffCode("28");
            users.add(user);
        }
    }

    private void dealGroupAdd(KitePosHandlerContext context, List<KitePosUserDTO> users, KiteSceneInst kiteSceneInst,
        String createDateStr, List<Map<String, Object>> groupUserInfos) {
        for (Map<String, Object> groupUserInfo : groupUserInfos) {
            KitePosUserDTO user = new KitePosUserDTO();
            user.setUserId(KiteMapUtils.getString(groupUserInfo, "user_id"));
            user.setSerialNumber(KiteMapUtils.getString(groupUserInfo, "serial_number").toUpperCase());
            user.setName(KiteMapUtils.getString(groupUserInfo, "user_name"));
            user.setInstanceId(SeqUtils.getNext("SEQ_USER_ID"));
            operateSceneInstService
                .putExtParameter(context.getSceneInstId(), "business_number", user.getSerialNumber());
            operateSceneInstService.putExtParameter(context.getSceneInstId(), "instanceId", user.getInstanceId());
            List<KitePosAttrDTO> attrList = new ArrayList<>();
            user.setOpenDate(KiteMapUtils.getString(groupUserInfo, "open_date"));
            String userLocation = querySceneInstService
                .getCommonAttrValue(context.getSceneInstId(), "user_location");
            if (!KiteStringUtils.isEmpty(userLocation)) {
                user.setProvinceCode(userLocation.split(",")[0]);
                user.setCityCode(userLocation.split(",").length > 1 ? userLocation.split(",")[1] : "");
                user.setDistrictCode(userLocation.split(",").length > 2 ? userLocation.split(",")[2] : "");
            }
            else {
                // 没有用户归属地属性，用客户的区域信息
                CuccContextCustDTO custDto = context.getCustDto();
                user.setProvinceCode(custDto.getProvinceCode());
                user.setCityCode(Optional.ofNullable(custDto.getLanId()).orElse(custDto.getEparchyCode()));
                user.setDistrictCode(Optional.ofNullable(custDto.getRegionId()).orElse(""));
            }
            this.addUserSourceAttr(attrList, groupUserInfo, createDateStr);
            this.packageUserAttrs(attrList, user, context, createDateStr);
            user.setUserDiffCode("28");
            users.add(user);
        }
    }

    private void packageUserAttrsJf(List<KitePosAttrDTO> attrList, KitePosUserDTO user, KitePosHandlerContext context, String createDateStr,String cateId) {

        List<KiteAttr> busiAttrs = Lists.newArrayList();
        busiAttrs.addAll(querySceneInstService.listCommonAttrsByModuleId(context.getSceneInstId(), LocalKeyConsts.CUSTMANAGERINFO_MODULEID));
        busiAttrs.addAll(querySceneInstService.listCommonAttrsByModuleId(context.getSceneInstId(), LocalKeyConsts.GROUPUSERINFO_MODULEID));
        busiAttrs = busiAttrs.stream().filter(attr -> !KiteStringUtils.equals(attr.getShowType(), LocalKeyConsts.KITE_ATTR_CONFIG_SHOW_TYPE_H) ||
            KiteStringUtils.equals(attr.getFieldName(), LocalKeyConsts.BUSINESS_NEW) ||
            KiteStringUtils.equals(attr.getFieldName(), LocalKeyConsts.VIK_BUSINESS_CODE) ||
            KiteStringUtils.equals(attr.getFieldName(), LocalKeyConsts.VIK_BUSINESS_CODE_NEW)).collect(Collectors.toList());
        busiAttrs = busiAttrs.stream().filter(attr -> isFilterFieldJf(attr.getFieldName())).collect(Collectors.toList());
        for (KiteAttr kiteAttr : busiAttrs) {
            if (!attrList.stream().anyMatch((attr) -> attr.getCode().equals(kiteAttr.getFieldName()))) {
                KitePosAttrDTO attr = new KitePosAttrDTO();

                attr.setCode(kiteAttr.getFieldName());
                attr.setType("STRING");
                attr.setStartDate(createDateStr);
                attr.setEndDate(LocalKeyConsts.ATTR_SEND_DATE);
                attr.setValue(kiteAttr.getValue() == null ? "" : kiteAttr.getValue());
                if (CuccPosServiceUtils.isProdModify(context.getSceneInstId())) {
                    // 属性不存在返回的用户属性中，初始值为空，当前值不为空，则视为新增操作
                    if (KiteStringUtils.isNotEmpty(kiteAttr.getValue()) && KiteStringUtils.isEmpty(kiteAttr.getOriginValue())) {
                        attr.setChangeType(ChangeTypeUtils.CHANGE_TYPE_A);
                    } else {
                        String changeType = KiteStringUtils.equals(kiteAttr.getOriginValue(), kiteAttr.getValue()) ? ChangeTypeUtils.CHANGE_TYPE_K : ChangeTypeUtils.CHANGE_TYPE_M;
                        attr.setChangeType(changeType);
//                      attr.setOriginValue(kiteAttr.getOriginValue());
                    }
                }
                attrList.add(attr);
            }
            else {
                //如果有匹配的属性并且值不相等,那么取场景中的数据更新转单
                KitePosAttrDTO posAttr = attrList.stream()
                    .filter(attr -> attr.getCode().equals(kiteAttr.getFieldName()) && !attr.getValue().equals(kiteAttr.getValue()))
                    .findFirst().orElse(null);
                if (Objects.nonNull(posAttr)) {
                    posAttr.setValue(kiteAttr.getValue() == null ? "" : kiteAttr.getValue());
                    if (CuccPosServiceUtils.isProdModify(context.getSceneInstId())) {
                        // 二次业务 如果属性是隐藏的, 并且值不相等，并且当前值为空，旧值不为空，就传删除动作
                        if (KiteStringUtils.equals(kiteAttr.getShowType(), LocalKeyConsts.KITE_ATTR_CONFIG_SHOW_TYPE_H) &&
                            KiteStringUtils.isEmpty(kiteAttr.getValue()) && KiteStringUtils.isNotEmpty(kiteAttr.getOriginValue())) {
                            // 删除动作，值不能为空，结束时间可不传或传竣工时间
                            posAttr.setValue(kiteAttr.getOriginValue());
                            posAttr.setEndDate(createDateStr);
                            posAttr.setChangeType(ChangeTypeUtils.CHANGE_TYPE_D);
                        } else {
                            String changeType = KiteStringUtils.equals(kiteAttr.getOriginValue(), kiteAttr.getValue()) ? ChangeTypeUtils.CHANGE_TYPE_K : ChangeTypeUtils.CHANGE_TYPE_M;
                            posAttr.setChangeType(changeType);
//                          posAttr.setOriginValue(kiteAttr.getOriginValue());
                        }
                    }
                }
            }
        }
        if(!KiteListUtils.isEmpty(attrList)) {
            attrList = attrList.stream().filter(attr -> isFilterFieldJf(attr.getCode())).collect(Collectors.toList());
            if (CuccPosServiceUtils.isProdModify(context.getSceneInstId())) {
                for (KitePosAttrDTO posAttr : attrList) {
                    if (KiteStringUtils.isEmpty(posAttr.getChangeType())) {
                        posAttr.setChangeType(ChangeTypeUtils.CHANGE_TYPE_K);
//                      posAttr.setOriginValue(posAttr.getValue());
                    }
                }
                List<KitePosAttrDTO> changeAttrList = attrList.stream().filter(attr -> KiteStringUtils.equals(attr.getChangeType(), ChangeTypeUtils.CHANGE_TYPE_M)).collect(Collectors.toList());
                if (KiteListUtils.isEmpty(changeAttrList)) {
                    user.setChangeType(ChangeTypeUtils.CHANGE_TYPE_K);
                } else {
                    user.setChangeType(ChangeTypeUtils.CHANGE_TYPE_M);
                }
            }
            user.setAttrs(attrList);
        }
    }

    private void packageGiftUserAttr(KitePosHandlerContext context, List<KitePosUserDTO> users, Map<String, KitePosOfferInstVO> giftOfferInstMap, String createDateStr) {
        Iterator<KitePosOfferInstVO> iterator = giftOfferInstMap.values().iterator();
        Map<String, KitePosOfferInstVO> mainOfferInstMap = context.getPosSceneBO().getMainOfferInstMap();
        while (iterator.hasNext()) {
            KitePosOfferInstVO offerInstVO = iterator.next();
            //套餐实例
            KiteOfferInst giftOfferInst = offerInstVO.getOfferInst(); //融合销售品实例

            //先处理融合本身
            KitePosUserDTO user = new KitePosUserDTO();
            String group_user_name = querySceneInstService.getCommonAttrValue(context.getSceneInstId(), "group_user_name");
            user.setUserId(getUserId(context.getSceneInstId(), giftOfferInst.getOfferInstId(), InstType.GIFT_OFFER_INST, context.getCustDto()));
            user.setSerialNumber(getSerialNumber(context));
            user.setName(group_user_name);
            CuccContextCustDTO custDto = context.getCustDto();
            user.setProvinceCode(custDto.getProvinceCode());
            user.setCityCode(Optional.ofNullable(custDto.getLanId()).orElse(custDto.getEparchyCode()));
            user.setDistrictCode(Optional.ofNullable(custDto.getRegionId()).orElse(""));
            user.setInstanceId(SeqUtils.getNext("SEQ_USER_ID"));
            user.setOfferCatagoryId(giftOfferInst.getAttrValue("cateId"));
            user.setOpenDate(createDateStr);
            // 0511 改造计费周期、付费类型、计费类型、缴费周期、账务周期放在user节点传给订单中心
            user.setChargeCycle(querySceneInstService.getCommonAttrValue(context.getSceneInstId(), "ORD10235"));
            user.setPayMode(querySceneInstService.getCommonAttrValue(context.getSceneInstId(), "ORD10236"));
            user.setBillType(querySceneInstService.getCommonAttrValue(context.getSceneInstId(), "ORD10240"));
            user.setFeeCycle(querySceneInstService.getCommonAttrValue(context.getSceneInstId(), "ORD10233"));
            user.setAccountCycle(querySceneInstService.getCommonAttrValue(context.getSceneInstId(), "ORD10234"));
            operateSceneInstService.putExtParameter(context.getSceneInstId(), "business_number", user.getSerialNumber());
            operateSceneInstService.putExtParameter(context.getSceneInstId(), "instanceId", user.getInstanceId());
            List<KitePosAttrDTO> attrList = new ArrayList<>();
            this.packageUserAttrs(attrList, user, context, createDateStr);
            users.add(user);
            //处理成员商品
            List<KitePosOfferObjInstRelVO> giftDetails = offerInstVO.getOfferObjInstRels(); //融合包含的成员商品
            for (KitePosOfferObjInstRelVO giftInstRel : giftDetails) {
                if (CoreDataOffer.OFF_C_0044_100000.equals(giftInstRel.getObjType())) {
                    continue;
                }
                KitePosUserDTO detailUser = new KitePosUserDTO();
                detailUser.setUserId(getUserId(context.getSceneInstId(), giftInstRel.getInstId(), InstType.MAIN_OFFER_INST, context.getCustDto()));
                detailUser.setName(group_user_name);
                detailUser.setProvinceCode(custDto.getProvinceCode());
                detailUser.setCityCode(Optional.ofNullable(custDto.getLanId()).orElse(custDto.getEparchyCode()));
                detailUser.setDistrictCode(custDto.getRegionId());
                detailUser.setOfferCatagoryId(giftInstRel.getCatagoryId());
                detailUser.setInstanceId(SeqUtils.getNext("SEQ_USER_ID"));
                detailUser.setUserDiffCode("-1");
                detailUser.setOpenDate(createDateStr);
                // 0511 改造计费周期、付费类型、计费类型、缴费周期、账务周期放在user节点传给订单中心
                detailUser.setChargeCycle(querySceneInstService.getCommonAttrValue(context.getSceneInstId(), "ORD10235"));
                detailUser.setPayMode(querySceneInstService.getCommonAttrValue(context.getSceneInstId(), "ORD10236"));
                detailUser.setBillType(querySceneInstService.getCommonAttrValue(context.getSceneInstId(), "ORD10240"));
                detailUser.setFeeCycle(querySceneInstService.getCommonAttrValue(context.getSceneInstId(), "ORD10233"));
                detailUser.setAccountCycle(querySceneInstService.getCommonAttrValue(context.getSceneInstId(), "ORD10234"));
                //成员的复用融合壳子的
                detailUser.setAttrs(user.getAttrs());
                String instId = giftInstRel.getInstId();
                KitePosOfferInstVO kitePosMainOfferInstVO = mainOfferInstMap.get(instId);
                List<KitePosOfferObjInstRelVO> objInstRels = kitePosMainOfferInstVO.getOfferObjInstRels(); //套餐销售品包含产品
                Map<String, KitePosProdInstVO> prodInstMap = context.getPosSceneBO().getProdInstMap();

                for (KitePosOfferObjInstRelVO instRel : objInstRels) {
                    String relInstIdId = instRel.getInstId();
                    KitePosProdInstVO prodInstVO = prodInstMap.get(relInstIdId);
                    KiteProdInst prodInst = prodInstVO.getProdInst();
                    KiteAttr busiNbrAttr = prodInst.getAttr("200002981");
                    if (Objects.isNull(busiNbrAttr)) {
                        continue;
                    }
                    detailUser.setSerialNumber(busiNbrAttr.getValue());
                }
                users.add(detailUser);
            }
        }
    }

    @SuppressWarnings("deprecation")
    private CuccCustInfoDTO queryNewCustInfo(String custId) {
        KiteCustomerInfoReq kiteCustomerInfoReq = new KiteCustomerInfoReq();
        CuccCustInfoDTO cuccCustInfoDTO = new CuccCustInfoDTO();
        kiteCustomerInfoReq.setCustId(custId);
        String staffCode = ContextUtil.getSimpleLoginInfo().getStaffCode();
        String eparchyCode = ContextUtil.getSimpleLoginInfo().getLanId();
        String provinceCode = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        kiteCustomerInfoReq.setStaffCode(staffCode);
        kiteCustomerInfoReq.setEparchyCode(eparchyCode);
        kiteCustomerInfoReq.setProvinceCode(provinceCode);
        kiteCustomerInfoReq.setPageNum(1);
        kiteCustomerInfoReq.setPageSize(10);
        // 调用查询客户列表
        PageInfo<CuccCustInfoDTO> list = custReceptionService.customerListQuery(kiteCustomerInfoReq);
        if (!KiteObjectUtils.isEmpty(list) && KiteListUtils.isNotEmpty(list.getList())) {
            List<CuccCustInfoDTO> cuccCustInfoDTOList = list.getList();
            cuccCustInfoDTO = cuccCustInfoDTOList.get(0);
        }
        return cuccCustInfoDTO;
    }


    private boolean isFilterFieldJf(String filedName) {
        boolean result = false;
        DcPublic dp = DcPublicCache.get("20210629001",filedName);
        if(Objects.nonNull(dp)) {
            result = true;
        }
        return result;
    }
    private boolean isFilterFieldByConfig(String filedName,List<KiteAttr> busiAttrs) {
        boolean result = true;
        result = Objects.nonNull(busiAttrs.stream()
            .filter(busiAttr -> KiteStringUtils.equals(busiAttr.getFieldName(),filedName))
            .findFirst().orElse(null));
        return result;
    }

}
